<script setup lang="ts">

import {computed, onMounted, reactive, ref} from "vue";
import {userStore} from "@/store/user.ts";
import {changePassword, User} from "@/api/sysController.ts";
import {Message} from "@arco-design/web-vue";

const userInfo: User = computed(() => userStore().userInfo)
const visible = ref()
const changeFormRef = ref()
const changePasswordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const rules = {
  oldPassword: [
    {required: true, message: '请输入原密码'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码'},
    {match: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/, message: '密码格式不正确，密码由8到16位数字、字母组成'}
  ],
  confirmPassword: [
    {required: true, message: '请确认新密码'},
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if(value !== changePasswordForm.newPassword) {
          callback('两次密码不一致')
        } else {
          callback()
        }
      }
    }
  ]
}

const openDialog = () => {
  visible.value = true
}
const handleSubmit = async (): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    changeFormRef.value.validate((error) => {
      if (!error) {
        changePassword(changePasswordForm).then(() => {
          resolve(true)
          visible.value = false
          changeFormRef.value.resetFields()
          Message.success('修改成功，请重新登录')
          setTimeout(() => {
            userStore().logout()
          }, 3000)
        }).catch(() => {
          reject(false)
        })
      } else {
        reject(error)
      }
    })
  })
}
</script>

<template>
  <div class="main">
    <a-page-header title="个人中心" :show-back="false"></a-page-header>
    <a-form :model="userInfo">
      <a-form-item label="用户名">
        <span>{{ userInfo.username }}</span>
      </a-form-item>
      <a-form-item label="角色">
        <span>{{ userInfo.role }}</span>
      </a-form-item>
    </a-form>
    <div class="handle-button">
      <a-button type="primary" @click="openDialog">修改密码</a-button>
    </div>

    <a-modal v-model:visible="visible" title="修改密码" :on-before-ok="handleSubmit" @close="changeFormRef.resetFields()">
      <a-alert style="margin-bottom: 20px;">密码需由8到16位数字、字母组成</a-alert>
      <a-form ref="changeFormRef" :model="changePasswordForm" :rules="rules">
        <a-form-item label="原密码" field="oldPassword">
          <a-input-password v-model="changePasswordForm.oldPassword"></a-input-password>
        </a-form-item>
        <a-form-item label="新密码" field="newPassword">
          <a-input-password v-model="changePasswordForm.newPassword"></a-input-password>
        </a-form-item>
        <a-form-item label="确认密码" field="confirmPassword">
          <a-input-password v-model="changePasswordForm.confirmPassword"></a-input-password>
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<style scoped lang="scss">
.main {
  padding-bottom: 50px;
}
.handle-button {
  margin-left: 280px;
}
</style>